package cn.hnu.service.impl;

import cn.hnu.domain.Users;
import cn.hnu.mapper.UserMapper;
import cn.hnu.service.EmailService;
import cn.hnu.service.UsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@RequiredArgsConstructor
@Transactional
public class UsersServiceImpl implements UsersService {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Users findUser(String username, String password) {
        Users user = userMapper.findByUsername(username);
        if(user == null || bCryptPasswordEncoder.matches(password, user.getPassword())) { //用户不存在或者密码错误
            return null;
        }
        return user;
    }

    @Override
    public boolean register(Users users) {
        // 根据用户名查找用户
        Users users1 = userMapper.findByUsername(users.getUsername());
        if(users1 != null) {
            return false; // 用户已存在，注册失败
        }
        // 根据邮箱查找用户
        users1 = userMapper.findByEmail(users.getEmail());
        if(users1 != null) {
            return false; // 邮箱已被使用，注册失败
        }
        users1 = new Users();
        users1.setUsername(users.getUsername());
        users1.setEmail(users.getEmail());
        users1.setRoleId(users.getRoleId());
        // 对密码进行加密
        users1.setPassword(bCryptPasswordEncoder.encode(users.getPassword()));
        // 保存到数据库
        userMapper.insert(users1);
        return true;
    }
}
